package com.tycmc.signelectroniccontracts.tools.images;

import android.content.Context;

import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.tycmc.signelectroniccontracts.tools.manager.AppManager;
import com.tycmc.signelectroniccontracts.tools.net.tools.SSLTool;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

public class AuthImageDownloader extends BaseImageDownloader {
    public AuthImageDownloader(Context context) {
        super(context);
    }

    public AuthImageDownloader(Context context, int connectTimeout, int readTimeout) {
        super(context, connectTimeout, readTimeout);
    }

    @Override
    public InputStream getStream(String imageUri, Object extra) throws IOException {
        if(imageUri.startsWith("https://")){
            URL url = new URL(imageUri);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setConnectTimeout(60000);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            SSLSocketFactory sslSocketFactory = SSLTool.getSSLSocketFactory(AppManager.getAppManager().currentActivity());
            if (sslSocketFactory != null) {
                conn.setSSLSocketFactory(sslSocketFactory);
            }
            InputStream is = conn.getInputStream();
            return is;
        }
        return super.getStream(imageUri, extra);
    }
}
